package cn.jietuo.first.class01;

import java.util.Arrays;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/26
 * @description: 插入排序
 */
public class Code03_InsertionSort {

    public static void insertionSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        for (int i = 1; i < arr.length ; i++) {
            // i = 0  j = 1  0~1有序
            // i = 1  j = 0  1~2有序
            // i = 3  j
            for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
                swap(arr, j, j + 1);
            }
        }
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 50;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            // 随机生成一个数字
            int[] randomArray = generateRandomArray(maxSize, maxValue);
            int[] copyArray = copyArray(randomArray);
            insertionSort(randomArray);
            compartorSort(copyArray);

            if(!isEqual(randomArray,copyArray)){
                succeed = false;
                printArray(randomArray);
                System.out.println();
                printArray(copyArray);
            }
        }
        System.out.println(succeed ? "Nice!" : "Oops!");
    }

    private static boolean isEqual(int[] arr1, int[] arr2) {
        if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) {
            return false;
        }
        if (arr1 == null && arr2 == null) {
            return true;
        }
        if (arr1.length != arr2.length) {
            return false;
        }
        for (int i = 0; i < arr1.length; i++) {
            if (arr1[i] != arr2[i]) {
                return false;
            }
        }
        return true;
    }

    private static void compartorSort(int[] copyArray) {
        Arrays.sort(copyArray);
    }

    private static int[] copyArray(int[] randomArray) {
        if (randomArray == null) {
            return null;
        }
        int[] array = new int[randomArray.length];
        for (int i = 0; i < randomArray.length; i++) {
            array[i] = randomArray[i];
        }
        return array;
    }

    private static void printArray(int[] randomArray) {
        for (int i = 0; i < randomArray.length; i++) {
            System.out.print(randomArray[i] + " ");
        }
    }

    private static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] array = new int[(int) ((maxSize + 1) * Math.random())];
        for (int i = 0; i < array.length; i++) {
            array[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
        }
        return array;
    }
}
